package dataAccess;

import logging.*;
import settings.*;

import java.io.*;
import java.util.concurrent.locks.*;

/**
 * Local data access class for the settings.txt file. 
 * @author BDS
 */
public class LocalDataAccess
{
	private static final Lock LOCK = new ReentrantLock();
	
	/**
	 * Static constructor.
	 */
	private LocalDataAccess() { }

	/**
	 * Loads the Settings from the settings.txt file.
	 * @return The Settings, read from the settings.txt file.
	 */
	public static Settings loadSettings()
	{
		Settings settings = new Settings();

		try
		{
			LOCK.tryLock();
			settings = (Settings) new ObjectInputStream(new FileInputStream(LocalDataAccess.getSettingsFilePath())).readObject();
		}
		catch (Exception exception)
		{
			Logger.logMessage("Error when reading settings file");
			Logger.logException(exception);
		}
		finally
		{
			LOCK.unlock();
		}

		return settings;
	}

	/**
	 * Saves the Settings.
	 * @param settings The Settings to save.
	 * @return True if successful; false otherwise.
	 */
	public static boolean saveSettings(Settings settings)
	{
		try
		{
			LOCK.tryLock();
			new File(LocalDataAccess.getSettingsFilePath()).delete();
			new File(LocalDataAccess.getSettingsFilePath()).createNewFile();
			new ObjectOutputStream(new FileOutputStream(LocalDataAccess.getSettingsFilePath())).writeObject(settings);
		}
		catch (Exception exception)
		{
			Logger.logMessage("Error when saving settings file");
			Logger.logException(exception);
		}
		finally
		{
			LOCK.unlock();
		}

		return false;
	}

	/**
	 * Getter for the full path of the settings.txt file.
	 * @return The full path of the settings.txt file.
	 */
	private static String getSettingsFilePath()
	{
		return System.getProperty("user.dir") + "\\settings.txt";
	}
}
